/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-18 19:25:13
 ******************************************************************************/
package cn.cmcc.online.smsapi.sdk.queue;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import cn.cmcc.online.smsapi.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.cmcc.online.smsapi.sdk.Iservice.XyCallBack;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.entity.ResourseManager;
import cn.cmcc.online.smsapi.sdk.dex.DexUtil;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.net.NetUtil;
import cn.cmcc.online.smsapi.sdk.net.util.ServerResposeParseUtil;
import cn.cmcc.online.smsapi.sdk.net.util.ServerUtil;
import cn.cmcc.online.smsapi.sdk.queue.util.ResourseUtil;
import cn.cmcc.online.smsapi.sdk.util.FileUtils;
import cn.cmcc.online.smsapi.sdk.util.JsonUtil;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;
import cn.cmcc.online.smsapi.sdk.util.XyUtil;

public class ResourseQueue extends Thread {

    static boolean isRun = false;// 是否正在下载中

    public synchronized static void runResourseQueue() {

        if (isRun == false && NetUtil.checkAccessNetWork(2)) {
            // 网络类型允许
            // 当队列线程序未运行时,才运行
            ResourseQueue queue = new ResourseQueue();
            queue.start();
        }

    }

    @Override
    public void run() {
        try {
            this.setName("xiaoyuan_resoursequeue");
            android.os.Process.setThreadPriority(SdkTaskQueue.XIAOYUAN_THREA_PRIORITY);
            if (isRun == false) {
                isRun = true;
                try {
                    Thread.sleep(1000);
                    checkResourse(ResourseUtil.RES_TYPE_LOGO);
                    Thread.sleep(1000);
                    downloadResourse(ResourseUtil.RES_TYPE_LOGO);
                    Thread.sleep(1000);
                    unzipResourse(ResourseUtil.RES_TYPE_LOGO);

                } catch (Throwable e) {
                    // TODO: handle Throwable
                }
                isRun = false;

            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "run: ", e);

        }

    }

    /**
     * 下载资源
     */
    public static void downloadResourse(int resType) {

        try {
            if (!NetUtil.checkAccessNetWork(2)) {
                /*sdk-593 hewengao/20160819 start*/
                LogManager.w("downloadResourse", "没有网络");
                /*sdk-593 hewengao/20160819 end*/
                return;
            }// 需要网络，假如网络都没有直接就不需要检查了

            JSONArray JsonArray = ResourseManager.queryNeedDownResourse(resType);
            if (JsonArray != null && JsonArray.length() > 0) {
                int size = JsonArray.length();
                for (int i = 0; i < size; i++) {
                    JSONObject json = JsonArray.getJSONObject(i);
                    String res_url = (String) JsonUtil.getValueFromJsonObject(json, "res_url");
                    Integer res_version = (Integer) JsonUtil.getValueFromJsonObject(json, "res_version");
                    Long down_failed_time = (Long) JsonUtil.getValueFromJsonObject(json, "down_failed_time");
                    Integer id = (Integer) JsonUtil.getValueFromJsonObject(json, "id");
                    if (!StringUtils.isNull(res_url)) {
                        long now = System.currentTimeMillis();
                        String fileName = resType + "_" + res_version + "_" + now + ".zip";
                        if (now > down_failed_time + DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_REDOWNLOAD_RESOURSE_CYCLE, 3600 * 1000L)) {
                            int result = -1;
                            try {
                                result = FileUtils.downFile(res_url, Constant.getPath("duoqu_temp"), fileName);
                            } catch (Throwable e) {
//                                e.printStackTrace();
                                LogManager.w(Constant.TAG, "downloadResourse: ", e);
                            }

                            if (result == 0) {// 下载成功
                                ResourseManager.UpdateResourse(id, true, fileName);
                                LogManager.d("downloadResourse", fileName,"下载成功");

                            } else {
                                // 下载失败
                                ResourseManager.UpdateResourse(id, false, fileName);
                                LogManager.d("downloadResourse", fileName,"下载失败了，这个类型的就不在继续");
                                // 下载失败了，这个类型的就不在继续
                                return;
                            }
                        } else {
                            LogManager.d("downloadResourse","还没超过1个小时，不能重复下载");
                            // 还没超过1个小时，不能重复下载
                            return;
                        }
                    }

                }
            }

        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "downloadResourse: ", e);

        }

    }

    /**
     * 解压资源，解压资源无需检查网络
     */
    public static void unzipResourse(int resType) {
        try {
            if (resType == ResourseUtil.RES_TYPE_LOGO) {
                List<File> list = ResourseUtil.getTempZip(resType + "");
                if (list != null && !list.isEmpty()) {
                    Iterator<File> it = list.iterator();
                    while (it != null && it.hasNext()) {
                        File file = it.next();
                        String fileName = file.getName();
                        boolean unzipsuccess = false;
                        try {
                            XyUtil.upZipFile(file, Constant.getPath("duoqu_publiclogo"));
                            // 解压成功，更新数据库里的状态
                            unzipsuccess = true;
                        } catch (Exception e) {

                        } finally {
                            try {
                                if (unzipsuccess) {
                                    file.delete();
                                }
                                ResourseManager.UpdateResourse(unzipsuccess, fileName);
                            } catch (Throwable e) {
//                                e.printStackTrace();
                                LogManager.e(Constant.TAG, "unzipResourse: ", e);

                            }

                        }

                    }
                }
            }// 其他资源，以后补充

        } catch (Throwable e) {
            // TODO: handle Throwable
        }
    }

    public static void checkResourse(int resType) {
        if (!NetUtil.checkAccessNetWork(2)) {
            return;
        }// 需要网络，假如网络都没有直接就不需要检查了
        if (ResourseUtil.isNeedCheck(resType)) {
            String version = ResourseManager.queryNeedCheckResourse(resType);
            if (StringUtils.isNull(version)) {
                version = "-1";
            }
            requestResourseQueue(version, resType);
        } else {
        }
    }

    public static void requestResourseQueue(String version, final int type) {

        try {

            XyCallBack callback = new XyCallBack() {
                @Override
                public void execute(Object... obj) {
                    try {
                        if (obj != null) {
                            String resutCode = obj[0].toString();
                            if (resutCode.equals("0") && obj.length == 2) {
                                String response = obj[1].toString();
                                ResourseUtil.updateCheckTime(type);
                                JSONArray result = ServerResposeParseUtil.parsecheckResourseResponse(response);

                                // 处理JSONArray,主要是入库，平且删除之前的旧版本
                                ResourseManager.handleJSONArray(result);
                            }
                        }
                    } catch (Throwable e) {
//                        e.printStackTrace();
                        LogManager.e(Constant.TAG, "requestResourseQueue: ", e);

                    }

                }
            };

            if (!StringUtils.isNull(version)) {
                if (NetUtil.checkAccessNetWork(2)) {
                    // 资源下载，受网络类型开关控制
                    /* SDK-504 huangzhiqiang 20160623 start */
                    String dataString = ServerUtil.getcheckResourseRequest(version, type);
                    if (!StringUtils.isNull(dataString)) {
                        NetUtil.executePubNumServiceHttpRequest(dataString, "990005", callback, "", true, false,
                                NetUtil.CheckResourseRequest, true);
                    }
                    /* SDK-504 huangzhiqiang 20160623 end */
                }

            }

        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "requestResourseQueue: ", e);

        }

    }

}
